import {GetUserInfo, UserLogin} from "../api/userApi";
import {setToken} from "../utils/token";
import {asyncRoutes, ordinaryRoutes} from "../router";
import router from "../router";
/**
 * 过滤路由
 * @param routes
 * @param roles
 * @returns {[]}
 */
export function filterAsyncRoutes(routes, roles) {
    const res = []
    routes.forEach(route => {
        const tmp = { ...route }
        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles)
            }
            res.push(tmp)
        }
    })
    return res
}

function hasPermission(roles, route) {
    if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role))
    } else {
        return true
    }
}

const actions = {
    /**
     * 用户登陆
     * @param commit
     * @param userInfo
     * @returns {Promise<unknown>}
     * @constructor
     */
    userLogin({commit},userInfo){
        const {username , password} = userInfo;
        return new Promise((resolve, reject) => {
            UserLogin(userInfo).then(res =>{
                console.log("结果 "+JSON.stringify(res))
                commit('Set_Token',res.data.data.token);
                setToken(res.data.data.token);
                commit('Set_Routes',ordinaryRoutes);
                resolve();
            }).catch(err =>{
                console.log("失败 "+err)
                reject();
            })
        })
    },

    /**
     * 获取用户信息
     * @param commit
     * @param state
     * @constructor
     */
    getUserInfo({commit , state}){
        console.log("getUserInfo")
        // return new Promise((resolve, reject) => {
        //     GetUserInfo(state.token).then(res =>{
        //         console.log("res "+res)
        //         resolve();
        //     }).catch(error =>{
        //         console.log("error "+error);
        //         reject();
        //     })
        // })
    },

    generateRoutes({commit},roles){
        return new Promise(resolve => {
            let accessedRoutes;
            if (roles.includes('admin')){
                accessedRoutes =asyncRoutes || []
            }
            else {
                accessedRoutes = filterAsyncRoutes(asyncRoutes,roles)
            }
            commit('Set_Routes',accessedRoutes)
            resolve(accessedRoutes)
        })
    },

}
export default actions